import 'dart:convert';
import 'package:http/http.dart' as http;

/// API服务类，用于处理与后端API的通信
class ApiService {
  static const String baseUrl = 'http://106.13.191.107:9800';
  
  /// 获取点位数据列表
  /// [moduleName] 模块名称
  /// [category] 分类名称
  static Future<List<Map<String, dynamic>>> getPointDataList({
    required String moduleName,
    required String category,
  }) async {
    try {
      final response = await http.post(
        Uri.parse('$baseUrl/api/point-data/getDataList'),
        headers: {
          'Content-Type': 'application/json',
        },
        body: jsonEncode({
          'module_name': moduleName,
          'category': category,
        }),
      );
      
      if (response.statusCode == 200) {
        final Map<String, dynamic> responseData = jsonDecode(response.body);
        
        print('API完整响应: ${response.body}');
        
        // 假设API返回格式为 {"code": 200, "data": [...], "message": "success"}
        if (responseData['code'] == 200 && responseData['data'] != null) {
          final data = List<Map<String, dynamic>>.from(responseData['data']);
          print('数据条数: ${data.length}');
          
          return data;
        } else {
          print('API返回错误: code=${responseData['code']}, message=${responseData['message']}');
          throw Exception('API返回错误: ${responseData['message'] ?? '未知错误'}');
        }
      } else {
        print('HTTP请求失败: ${response.statusCode}, body: ${response.body}');
        throw Exception('HTTP请求失败: ${response.statusCode}');
      }
    } catch (e) {
      print('获取点位数据失败: $e');
      rethrow; // 重新抛出异常，让调用方处理
    }
  }
  
  /// 获取房间排风控制数据
  static Future<List<Map<String, dynamic>>> getRoomExhaustControlData() async {
    return await getPointDataList(
      moduleName: '维护数据',
      category: '房间防风控制',
    );
  }
}